<template>
  <div>
    <el-card class="table-card">
      <div slot="header">
        <h3>{{isEdit ? '原材料编辑' : '原材料新增'}}</h3>
      </div>
      <el-row type="flex" justify="end">
        <el-button
          type="text"
          size="large"
          @click="handleSubmit"
          :loading="submitLoading"
          >提交</el-button
        >
        <el-button type="text" size="large" @click="$router.go(-1)"
          >返回</el-button
        >
      </el-row>
      <el-row>
        <skus-table
          :showActionCol="!isEdit"
          :columns="tableInfo.columns"
          :loading="tableInfo.loading"
          :dataSource="tableInfo.list"
          :actionRender="tableBtnAction"
        >
          <div slot="content_context">
            <el-button
              v-if="!isEdit"
              type="text"
              size="mini"
              icon="el-icon-plus"
              @click="handleAdd"
            >添加行</el-button
            >
          </div>
        </skus-table>
      </el-row>
    </el-card>
    <!-- 选择计量单位弹框 -->
    <SelectUnitDialog
      :visible.sync="mainUnitVisible"
      @getUnitInfo="handleReturnMainUnitName"
    />
  </div>
</template>
<script>
import SkusTable from '@/components/skusTable';
import { mapGetters } from 'vuex';
import { getAddTableColumns, EIDT_TABLE_COLUMNS } from './constants';
import { setAuthBtnId } from '@/utils/bizUtils';
import {
  queryMaterialDetailService,
  addMaterialService,
  updateMaterialService
} from '@/api/finance/rawMaterialManage/rawMaterial';
import { getUnitInfoListService } from '@/api/commodity/common';
import SelectUnitDialog from '@/pages/commodity/components/SelectUnitDialog';
import RemoteSelect from '@/pages/commodity/components/RemoteSelect';

export default {
  components: {
    SkusTable,
    SelectUnitDialog,
    RemoteSelect
  },
  data () {
    return {
      RemoteSelect: () => import('@/pages/commodity/components/RemoteSelect'),
      key: 1,
      mainUnitVisible: false,
      submitLoading: false,
      tableInfo: {
        list: [],
        columns: [],
        loading: false
      },
      idList: [],
      storageCurrentRowData: {}
    };
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
    isEdit () {
      return this.idList.length !== 0;
    }
  },
  watch: {
    id (val) {
      this.uploadParams = {
        id: val
      };
    }
  },
  created () {
    const { idList } = this.$route.params;
    if (idList) {
      this.idList = idList;
      this.getTableData();
    }
    this.initTableColumn();
  },
  methods: {
    initTableColumn () {
      this.tableInfo.columns = this.isEdit ? EIDT_TABLE_COLUMNS : getAddTableColumns(this);
      if (!this.isEdit) {
        this.handleAdd()
      }
    },
    // 渲染表格操作栏按钮
    tableBtnAction (h, { index, row }) {
      return (
        <div class="table-action">
          <el-button type="text" onClick={() => this.handleDelete(index)}>
            删除
          </el-button>
        </div>
      );
    },
    // 获取表格数据
    async getTableData () {
      setAuthBtnId();
      const data = this.idList
      const { retData } = await queryMaterialDetailService(
        data,
        state => { this.tableInfo.loading = state }
      );
      if (retData) {
        this.tableInfo.list = retData.list.map((item) => {
          return {
            id: item.id,
            name: item.name,
            spec: item.spec,
            unitName: item.unitName,
            unitUuid: item.unitUuid,
            producer: item.producer,
            price: item.price,
            warningType: item.warningType,
            warningValue: item.warningValue,
            warningPrice: item.warningPrice,
            warningDesc: item.warningDesc,
            priceSourceType: item.priceSourceType,
            priceSource: item.priceSource,
            website: item.website,
            companyName: item.companyName,
            telephone: item.telephone,
            warningTypeStr: item.warningTypeStr,
            warningPriceStartDate: item.warningPriceStartDate,
          }
        });
      }
    },
    // 提交新增原材料
    async addMaterialAction (data) {
      const res = await addMaterialService(
        data,
        state => { this.submitLoading = state }
      );
      if (res?.retStatus) {
        this.submitSuccessCallback()
      }
    },
    // 提交修改原材料
    async editMaterialAction (data) {
      const res = await updateMaterialService(
        data,
        state => { this.submitLoading = state }
      );
      if (res?.retStatus) {
        this.submitSuccessCallback()
      }
    },
    submitSuccessCallback () {
      this.$message.success('提交成功')
      this.$router.go(-1)
    },
    // 提交
    handleSubmit () {
      if (!this.tableInfo.list.length) {
        return this.$message.warning('请添加数据')
      }
      // 校验固定必填字段
      const requiredFields = this.tableInfo.columns.filter(item => item.required).map(item => item.key)
      let hasEmptyVal = false
      this.tableInfo.list.map((item) => {
        Object.keys(item).forEach(ele => {
          if (requiredFields.includes(ele) && item[ele] !== 0 && !item[ele]) {
            hasEmptyVal = true;
          }
        })
      })
      if (hasEmptyVal) {
        return this.$message.warning('请完善必填字段')
      }
      // 校验动态必填字段
      const hasOtherEmptyVal = this.tableInfo.list.some((item) => {
        return item.priceSourceType == 1 && (!item.priceSource || !item.website)
      })
      if (hasOtherEmptyVal) {
        return this.$message.warning('价格来源类型为线上网站时，价格来源、网址为必填项')
      }
      // 校验动态必填字段
      const hasOther1EmptyVal = this.tableInfo.list.some((item) => {
        return item.priceSourceType == 2 && (!item.companyName || !item.telephone)
      })
      if (hasOther1EmptyVal) {
        return this.$message.warning('价格来源类型为线下生产商时，公司名称、联系电话为必填项')
      }
      // 校验当前价格须大于0
      const hasEmptyPrice = this.tableInfo.list.some((item) => {
        return !item.price || item.price <= 0
      })
      if (hasEmptyPrice) {
        return this.$message.warning('当前价格须大于0')
      }
      if (this.isEdit) {
        // 当前价格 price 浮动预警值类型 warningType 比列1 金额2
        let superFloating = this.tableInfo.list.filter((item) => {
          if (item.warningType == 2) {
            // （当前价格≥预警起始价格+浮动预警值） 或（当前价格≤预警起始价格-浮动预警值）
            return (item.price >= item.warningPrice + item.warningValue || item.price <= item.warningPrice - item.warningValue)
          }
          if (item.warningType == 1) {
            // （当前价格≥预警起始价格*（1+浮动预警值/100） 或（当前价格≤预警起始价格*（1-浮动预警值/100）
            return (item.price >= item.warningPrice * (1 + (item.warningValue / 100)) || item.price <= item.warningPrice * (1 - (item.warningValue / 100)))
          }
        })
        if (superFloating.length != 0) {
          const nameList = superFloating.map(item => item.name)
          return this.$confirm(`本次修改原材料:${nameList},超浮动预警值，会对对应供应商推送待办提醒，确认提交吗？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.editMaterialAction(this.tableInfo.list)
          }).catch(() => {});
        } else {
          this.editMaterialAction(this.tableInfo.list)
        }
      } else {
        this.addMaterialAction(this.tableInfo.list)
      }
    },
    // 新增行
    handleAdd () {
      this.tableInfo.list.push(
        {
          key: this.key++,
          name: '',
          spec: '',
          unitName: '',
          unitUuid: '',
          producer: '',
          price: '',
          warningType: 1,
          warningValue: '',
          warningDesc: '',
          priceSourceType: '',
          priceSource: '',
          website: '',
          companyName: '',
          telephone: ''
        }
      )
    },
    // 删除行
    handleDelete (index) {
      this.tableInfo.list.splice(index, 1);
    },
    /* 选择主计量单位 */
    handleChooseMainUnit (data) {
      this.mainUnitVisible = true;
      this.storageCurrentRowData = data;
    },
    /* 获取选择的主计量单位值 */
    handleReturnMainUnitName (unitInfo) {
      const { uuid, unitName } = unitInfo;
      this.storageCurrentRowData.unitUuid = uuid;
      this.storageCurrentRowData.unitName = unitName;
    },
    // 获取计量单位查询入参
    getUnitSearchParams (unitName) {
      return {
        nowPage: 1,
        pageShow: 20,
        searchParam: JSON.stringify([
          { name: 'unitName', value: unitName },
          { name: 'unitName_q', value: 'Like' }
        ])
      }
    },
    // 计量单位模糊搜索
    async remoteOptionsByUnit (queryString, loadingFn) {
      console.log(queryString)
      const data = this.getUnitSearchParams(queryString);
      const retData = await getUnitInfoListService(data, loadingFn);
      if (retData) {
        let unitList = retData.results && retData.results.map((item) => (
          {
            unitUuid: item.uuid,
            unitName: item.unitName,
          }
        ))
        return unitList;
      }
      return [];
    },
    // 获取模糊搜索计量单位
    getUnitByRemote (data, row) {
      const { unitName, unitUuid } = data;
      row.unitName = unitName;
      row.unitUuid = unitUuid;
    },
  }
};
</script>
<style scoped>
.upload-wrap {
  margin-right: 10px;
}
.tooltip li {
  margin-bottom: 5px;
}
</style>
